package 剑指offer;

import java.util.Stack;

public class SymbolMatch {
    public static boolean sMatch(Character a, Character b) {
        switch (a) {
            case '{':
                return b == '}';
            case '(':
                return b == ')';
            case '[':
                return b == ']';
        }
        return false;
    }

    public static boolean match(String str) {
        String strLeft = "{[(";
        String strRiht = "}])";
        Stack<Character> stacks = new Stack<>();
        for (int i = 0; i < str.length(); i++) {
            Character a = str.charAt(i);
            if (!strLeft.contains(String.valueOf(a)) && !strRiht.contains(String.valueOf(a))) {
                return false;
            } else if (strLeft.contains(String.valueOf(a))) {
                stacks.push(a);
            } else if (strRiht.contains(String.valueOf(a))) {
                if (!stacks.isEmpty() && sMatch(stacks.peek(), a)) {
                    stacks.pop();
                    continue;
                }
                return false;

            }

        }
        return stacks.isEmpty();
    }

    public static boolean matchSecond(String str) {
        String strLeft = "{[(";
        String strRiht = "}])";
        if (str.length() % 2 == 0) {
            for (int i = 0; i < str.length(); i++) {
                Character a = str.charAt(i);
                if (!strLeft.contains(String.valueOf(a)) && !strRiht.contains(String.valueOf(a))) {
                    return false;
                } else if (strRiht.contains(String.valueOf(a))) {
                    if (i == str.length() >> 1) {
                        int index = i - 1;
                        while (index >= 0) {
                            if (sMatch(str.charAt(index), str.charAt(i))) {
                                index--;
                                i++;
                                continue;
                            }
                            return false;
                        }
                        return true;
                    }

                }

            }

        }

        return false;
    }

    public static void main(String[] args) {

        System.out.println(matchSecond("()[]{}"));

    }
}
